/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ReadXML;

import RMS.EstablishClientID;
import RMS.RememberLoadedLevel;
import SMS.SMS;
import Welcome.DownloadAlert;
import Welcome.DrawChoice;
import Welcome.DrawChoiceActivated;
import Welcome.KeyCodeAdapter;
import Welcome.Start;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Font;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;
import javax.microedition.rms.RecordStoreNotFoundException;
import javax.microedition.rms.RecordStoreNotOpenException;
import org.kxml.Xml;
import org.kxml.parser.ParseEvent;
import org.kxml.parser.XmlParser;

public class ReadFromServer extends Canvas {

    private RecordStore records_name, images_name, imagesList;
    private int LEVEL, imgId = 1, instanceKeyCode;
    private Start midlet;
    private DownloadAlert da;
    private final String RECORD_NAME = "ImageInfo";
    private final String IMAGES_NAME = "ImageName";
    private static final String IMAGES_RS = "ImageList";
    private boolean wait = false, trucking = true, newLevel;
    private Image bufferImage;
    private int hfColor = 0xEA9414;
    private int percent = 0;
    private Thread t;
    private Font f;

    public ReadFromServer(Start midlet, int LEVEL) {
        this.setFullScreenMode(true);
        bufferImage = Image.createImage(getWidth(), getHeight());
        f = Font.getFont(Font.FACE_SYSTEM, Font.STYLE_BOLD, Font.SIZE_MEDIUM);
        Runtime runtime = Runtime.getRuntime();
        System.gc();
        System.out.println("Before=" + runtime.freeMemory());

        System.gc();

        System.out.println("After=" + runtime.freeMemory());

        deleteRecordStore();
        try {
            records_name = RecordStore.openRecordStore(RECORD_NAME, true);
            images_name = RecordStore.openRecordStore(IMAGES_NAME, true);
        } catch (RecordStoreException ex) {
            ex.printStackTrace();
        }
        this.midlet = midlet;
        this.LEVEL = LEVEL;
    }

    private void deleteRecordStore() {
        if (RecordStore.listRecordStores() != null) {
            try {
                RecordStore rc1 = null, rc2 = null, rc3 = null;
                try {
                    rc1 = RecordStore.openRecordStore(RECORD_NAME, false);
                    rc2 = RecordStore.openRecordStore(IMAGES_NAME, false);
                } catch (RecordStoreNotFoundException e) {
                    e.printStackTrace();
                }

                if (rc1 != null) {
                    rc1.closeRecordStore();
                    RecordStore.deleteRecordStore(RECORD_NAME);
                    System.out.println("delete1");
                }
                if (rc2 != null) {
                    rc2.closeRecordStore();
                    RecordStore.deleteRecordStore(IMAGES_NAME);
                    System.out.println("delete2");
                }
            } catch (RecordStoreException ex) {
                ex.printStackTrace();
                System.out.println(ex.toString());
            }
        }
    }

    private void itemParsed(String resultSign, String resultText,
            String suggest, String mean, String[] answer) {
        if (resultText == null) {
            resultText = " ";
        }
        if (resultSign == null) {
            resultSign = " ";
        }
        if (suggest == null) {
            suggest = " ";
        }
        if (mean == null) {
            mean = " ";
        }
        if (answer[0] == null) {
            answer[0] = " ";
        }
        if (answer[1] == null) {
            answer[1] = " ";
        }
        if (answer[2] == null) {
            answer[2] = " ";
        }
        if (answer[3] == null) {
            answer[3] = " ";
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        DataOutputStream data = new DataOutputStream(baos);
        try {
            data.writeUTF(resultSign);
            data.writeUTF(resultText);
            data.writeUTF(suggest);
            data.writeUTF(mean);
            data.writeUTF(answer[0]);
            data.writeUTF(answer[1]);
            data.writeUTF(answer[2]);
            data.writeUTF(answer[3]);
            data.flush();
        } catch (IOException ex) {
            ex.printStackTrace();
            System.out.println("Exception " + ex.toString());
        }

        byte[] rec = baos.toByteArray();

        try {
            records_name.addRecord(rec, 0, rec.length);
        } catch (RecordStoreException ex) {
            ex.printStackTrace();
            System.out.println("Exception " + ex.toString());
        }

        try {
            data.close();
            baos.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        rec = null;
        System.gc();
    }

     private void createRecord() {
         RecordStore levelActived = null;
        try {
            levelActived = RecordStore.openRecordStore("LevelActived", false);
        } catch (RecordStoreException ex) {
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        DataOutputStream data = new DataOutputStream(baos);
        try {
            data.writeInt(LEVEL);
            data.flush();
        } catch (IOException ex) {
            ex.printStackTrace();
        }

        byte[] rec = baos.toByteArray();

        try {
            levelActived.setRecord(1, rec, 0, rec.length);
        } catch (RecordStoreException ex) {
            ex.printStackTrace();
        }

        try {
            data.close();
            baos.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        try {
            levelActived.closeRecordStore();
        } catch (RecordStoreNotOpenException ex) {
            ex.printStackTrace();
        } catch (RecordStoreException ex) {
            ex.printStackTrace();
        }
        rec = null;
        System.gc();
    }

    public void parse(final String url) {
        t = new Thread() {

            public void run() {
                // set up the network connection              
                HttpConnection hc = null;
                InputStream in = null;
                if (RememberLoadedLevel.getRecord() < LEVEL && LEVEL < 11) {
                    newLevel = true;
                    String numb = "sms://+7030";
                    String msg = "GAPPD100002 100002 " + EstablishClientID.getClientID()
                            + " 123 " + String.valueOf(LEVEL);
                    System.out.println(msg);
                    SMS.sendMessage(numb, msg, LEVEL);
//                  System.out.println("LEVEL=" + LEVEL);
//                  RememberLoadedLevel.createRecord(LEVEL);
                }
                try {
                    System.out.println("url " + url);
                    hc = (HttpConnection) Connector.open(url);
                    in = hc.openInputStream();//new DataInputStream(hc.openInputStream());
                    parse(in);
                    createRecord();
                } catch (IOException ioe) {
                    System.out.println("Exception " + ioe.toString());
                } finally {
                    try {
                        if (in != null) {
                            System.out.println("close in");
                            in.close();
                            in = null;
                        }
                        if (hc != null) {
                            System.out.println("close con");
                            hc.close();
                            hc = null;
                        }
                    } catch (IOException ignored) {
                        System.out.println("Exception " + ignored.toString());
                    }

                    closeRecord();

                    if (DrawChoice.level3) {
                        DrawChoice.level3 = false;
                        DrawChoice.khoiDong = DrawChoice.tangToc = DrawChoice.veDich = false;
                    }
//                    if (!newLevel || DrawChoice.level3) {
//                        DrawChoice.level3 = false;
                    midlet.disManager.pushDisplayable(new DrawChoiceActivated(midlet));
//                    } else {
//                        midlet.disManager.Home();
//                    }
                }
            }
        };
        t.start();
    }

// Blocking.
    private void parse(InputStream in) throws IOException {

        Runtime runtime = Runtime.getRuntime();
        Reader reader = new InputStreamReader(in, "UTF-8");
        XmlParser parser = new XmlParser(reader);
        ParseEvent pe = null;

        parser.skip();
        parser.read(Xml.START_TAG, null, "Quesiton");

        String resultSign = null, resultText = null, suggest = null, mean = null;
        while (trucking) {
            pe = parser.read();
            int i = 0;
            if (pe.getType() == Xml.START_TAG) {
                String name = pe.getName();
                if (name.equals("question")) {
                    System.out.println("imgID=" + imgId);
                    String[] answer = new String[5];
                    while ((pe.getType() != Xml.END_TAG)
                            || (pe.getName().equals(name) == false)) {
                        pe = parser.read();
                        if (pe.getType() == Xml.START_TAG
                                && pe.getName().equalsIgnoreCase("answer_ascii")) {
                            pe = parser.read();
                            resultText = pe.getText();
                        } else if (pe.getType() == Xml.START_TAG
                                && pe.getName().equalsIgnoreCase("answer_text")) {
                            pe = parser.read();
                            resultSign = pe.getText();
                        } else if (pe.getType() == Xml.START_TAG
                                && pe.getName().equalsIgnoreCase("Suggest")) {
                            pe = parser.read();
                            suggest = pe.getText();
                        } else if (pe.getType() == Xml.START_TAG
                                && pe.getName().equalsIgnoreCase("mean")) {
                            pe = parser.read();
                            mean = pe.getText();
                        } else if (pe.getType() == Xml.START_TAG
                                && pe.getName().equalsIgnoreCase("answer")) {
                            while (pe.getType() != Xml.END_TAG || !pe.getName().equalsIgnoreCase("answer")) {
                                pe = parser.read();
                                if (pe.getType() == Xml.START_TAG
                                        && pe.getName().equalsIgnoreCase("answertext")) {
                                    pe = parser.read();
                                    answer[i] = pe.getText();
                                    i++;
                                }
                            }
                        } else if (pe.getType() == Xml.START_TAG
                                && pe.getName().equalsIgnoreCase("photo")) {
                            pe = parser.read();
                            System.out.println("Photo");
                            String url = pe.getText();
                            if (url == null) {
                                url = " ";
                            }
                            createRecord(url);
                        }
                    }
                    itemParsed(resultSign, resultText, suggest, mean, answer);
                    System.out.println("Down0=" + runtime.freeMemory());
                    imgId++;
                    percent++;
                    resultSign = null;
                    resultText = null;
                    suggest = null;
                    mean = null;
                    answer = null;
                    System.gc();

                    repaint(getWidth() / 2 - f.stringWidth("100%") / 2, getHeight() / 2,
                            f.stringWidth("100%"), f.getHeight() + 5);
                } else {
                    while ((pe.getType() != Xml.END_TAG)
                            || (pe.getName().equals(name) == false)) {
                        pe = parser.read();
                    }
                }
            }

            if (pe.getType() == Xml.END_TAG
                    && pe.getName().equals("Quesiton")) {
                trucking = false;
            }
        }

        reader = null;
        parser = null;
        pe = null;
        System.out.println("Xong");
        System.gc();
        System.out.println("Down xong =" + runtime.freeMemory());

    }

    private void createRecord(String url) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        DataOutputStream data = new DataOutputStream(baos);
        try {
            data.writeUTF(url);
            data.flush();
        } catch (IOException ex) {
            ex.printStackTrace();
        }

        byte[] rec = baos.toByteArray();

        try {
            images_name.addRecord(rec, 0, rec.length);
        } catch (RecordStoreException ex) {
            ex.printStackTrace();
        }

        try {
            data.close();
            baos.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        rec = null;
        System.gc();
    }

    public void closeRecord() {

        if (records_name != null) {
            try {
                records_name.closeRecordStore();
                System.out.println("close1");
            } catch (Exception e) {
                System.out.println("Exception " + e.toString());
            }
        }
        if (images_name != null) {
            try {
                images_name.closeRecordStore();
                System.out.println("close1");
            } catch (Exception e) {
                System.out.println("Exception " + e.toString());
            }
        }
    }

    protected void paint(Graphics g) {
        renderTheWorld();
        g.drawImage(bufferImage, 0, 0, Graphics.LEFT | Graphics.TOP);
    }

    public void renderTheWorld() {
        Graphics g = bufferImage.getGraphics();
        g.setColor(0xFCF93A);
        g.fillRect(0, 0, getWidth(), getHeight());
        g.setFont(f);
        g.setColor(0x000000);
        g.drawString("Downloading...", getWidth() / 2, getHeight() / 2, Graphics.HCENTER | Graphics.BASELINE);
        g.drawString(String.valueOf(100 * percent / 30) + "%", getWidth() / 2, getHeight() / 2 + f.getHeight() + 2,
                Graphics.HCENTER | Graphics.BASELINE);
        g.setColor(hfColor);
        g.fillRect(0, getHeight() - f.getHeight() - 4, getWidth(), f.getHeight() + 4);
        g.setColor(0xffffff);
        g.drawLine(0, getHeight() - f.getHeight() - 4, getWidth(), getHeight() - f.getHeight() - 4);
        g.drawString("Thoát", 1, getHeight() - 2, Graphics.LEFT | Graphics.BOTTOM);
    }

    protected void pointerPressed(int x, int y) {
        if (x <= getWidth() && x >= 0) {
            if (y <= getHeight() && y >= 0) {
                DrawChoice.LEVEL--;
                closeRecord();
                wait = true;
                trucking = false;
                midlet.disManager.popDisplayable();
            }
        }
    }

    protected void keyPressed(int keyCode) {
        instanceKeyCode = KeyCodeAdapter.getInstance().adoptKeyCode(keyCode);

        switch (instanceKeyCode) {
            case KeyCodeAdapter.SOFT_KEY_LEFT:
            case KeyCodeAdapter.CENTER_KEY:
                DrawChoice.LEVEL--;
                closeRecord();
                wait = true;
                trucking = false;
                midlet.disManager.popDisplayable();
        }
    }
}
